package api

import (
	"context"
	"github.com/gin-gonic/gin"
	"log"
	"micro-server/middleware"
	"micro-server/modules/grpc/client"
	"micro-server/modules/grpc/funcStruct"
	"micro-server/public"
	"micro-server/router/routerInit"
	"micro-server/vender/grpcClient/input"
)

type Api struct{}

func RegisterGRpcClient() {
	api := Api{}
	routerInit.ApiNormalGroup.Handle("POST", "grpc_consul", api.gRpcClientConsul)
}

func (a *Api) gRpcClientConsul(gc *gin.Context) {
	defer public.TimeCost()()
	params := &input.Client{}
	if err := params.BindingParams(gc); err != nil {
		middleware.ErrorOut(gc, middleware.PARMAS_ERROR, err)
		return
	}
	result := gRpcClientConsul(params.Key, params.Limit)
	middleware.SuccessOut(gc, result, middleware.SUCCESS)
	return
}

func gRpcClientConsul(key string, limit int) (result *funcStruct.Reply) {
	args := &funcStruct.Args{
		Key:   key,
		Limit: limit,
	}
	reply := &funcStruct.Reply{}
	err := client.AddClient.Call(context.Background(), "Get", args, reply)
	if err != nil {
		log.Fatalf("failed to call: %v", err)
	}
	result = reply
	return
}
